import _ from 'lodash'
import browsers from './browsers.js'

// 辅助函数
function ensureIterable(value, defaultValue) {
    if (value === undefined || value === null) {
        return [...defaultValue];
    }
    if (typeof value === 'string') {
        return [value];
    }
    if (Array.isArray(value)) {
        return [...value];
    }
    throw new TypeError(`Value must be iterable or string but got ${typeof value}`);
}

function ensureFloat(value, defaultValue) {
    const num = parseFloat(value);

    if (isNaN(num)) {
        if (arguments.length >= 2) return defaultValue;
        throw new ValueError(`Value must be convertible to float but got ${value}`);
    }

    return num;
}

// 默认浏览器
const defaultBrowsers = [
    'Google', 'Chrome', 'Firefox', 'Edge', 'Opera', 'Safari', 'Android',
    'Yandex Browser', 'Samsung Internet', 'Opera Mobile', 'Mobile Safari',
    'Firefox Mobile', 'Firefox iOS', 'Chrome Mobile', 'Chrome Mobile iOS',
    'Mobile Safari UI/WKWebView', 'Edge Mobile', 'DuckDuckGo Mobile',
    'MiuiBrowser', 'Whale', 'Twitter', 'Facebook', 'Amazon Silk'
];

// 默认操作系统
const defaultOS = [
    'Windows', 'Linux', 'Ubuntu', 'Chrome OS', 'Mac OS X',
    'Android', 'iOS'
];

// 默认平台
const defaultPlatforms = [
    'desktop', 'mobile', 'tablet'
];

// 默认安全属性
const defaultSafeAttrs = ['shape'];

// 默认浏览器 User-Agent
const defaultUserAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0';


export default class FakeUserAgent {
    constructor(options = {}) {
        // 初始化数据
        this.initData(options);

        // 加载数据文件
        this.data = this.loadData();
    }

    initData(options) {
        this.browsers = ensureIterable(options.browsers, defaultBrowsers);
        this.os = ensureIterable(options.os, defaultOS);
        this.minVersion = ensureFloat(options.minVersion, 0.0);
        this.minPercentage = ensureFloat(options.minPercentage, 0.0);
        this.platforms = ensureIterable(options.platforms, defaultPlatforms);
        this.fallback = options.fallback || defaultUserAgent
        this.safeAttrs = new Set(ensureIterable(options.safeAttrs, defaultSafeAttrs));
    }

    loadData() {
        return browsers
        // try {
        //     const dataPath = path.join(__dirname, 'browsers.json');
        //     const rawData = fs.readFileSync(dataPath, 'utf-8');
        //     return JSON.parse(rawData);
        // } catch (error) {
        //     console.error('Error loading browser data:', error);
        //     return [];
        // }
    }

    getBrowser(browsers = 'random') {
        try {
            let filtered;
            if (browsers === 'random') {
                filtered = this.filterUserAgents();
            } else {
                filtered = this.filterUserAgents(browsers);
            }
            
            if (filtered.length === 0) {
                return this.createFallback();
            }

            return _.sample(filtered);
        } catch (error) {
            console.warn('Error getting browser:', error);
            return this.createFallback();
        }
    }

    filterUserAgents(browsersToFilter) {
        let filtered = this.data.filter(item => 
            this.browsers.includes(item.browser) &&
            this.os.includes(item.os) &&
            this.platforms.includes(item.type) &&
            item.browser_version_major_minor >= this.minVersion &&
            item.percent >= this.minPercentage
        );

        if (browsersToFilter && browsersToFilter !== 'random') {
            const targets = ensureIterable(browsersToFilter, []);
            filtered = filtered.filter(item => targets.includes(item.browser));
        }

        return filtered;
    }

    createFallback() {
        return {
            useragent: this.fallback,
            percent: 100.0,
            type: 'desktop',
            device_brand: null,
            browser: 'Edge',
            browser_version: '122.0.0.0',
            browser_version_major_minor: 122.0,
            os: 'win32',
            os_version: '10',
            platform: 'Win32'
        };
    }

    // 属性访问方法
    get chrome() {
        return this.getBrowser(['Chrome', 'Chrome Mobile', 'Chrome Mobile iOS']).useragent;
    }

    get googlechrome() {
        return this.chrome;
    }

    get ff() {
        return this.firefox;
    }

    get firefox() {
        return this.getBrowser(['Firefox', 'Firefox Mobile', 'Firefox iOS']).useragent;
    }

    get safari() {
        return this.getBrowser(['Safari', 'Mobile Safari']).useragent;
    }

    get opera() {
        return this.getBrowser(['Opera', 'Opera Mobile']).useragent;
    }

    get google() {
        return this.getBrowser(['Google']).useragent;
    }

    get edge() {
        return this.getBrowser(['Edge', 'Edge Mobile']).useragent;
    }

    get random() {
        return this.getBrowser('random').useragent;
    }

    // 完整数据访问方法
    get getChrome() {
        return this.getBrowser(['Chrome', 'Chrome Mobile', 'Chrome Mobile iOS']);
    }

    get getFirefox() {
        return this.getBrowser(['Firefox', 'Firefox Mobile', 'Firefox iOS']);
    }

    get getSafari() {
        return this.getBrowser(['Safari', 'Mobile Safari']);
    }

    get getOpera() {
        return this.getBrowser(['Opera', 'Opera Mobile']);
    }

    get getGoogle() {
        return this.getBrowser(['Google']);
    }

    get getEdge() {
        return this.getBrowser(['Edge', 'Edge Mobile']);
    }

    get getRandom() {
        return this.getBrowser('random');
    }
}